from simulation.evaluation.evaluation import * #get_rand_index_and_f_measure, accuracy
from simulation.utils.FIleAndPrint import readFileToArray, readTxAndFromFileToArray
from mycluster.cluster_function import my_SpectralCoclustering, my_kmeans, my_AffinityPropagation

if __name__ == '__main__':
    filepath = "D://project//IDEA//仿真实验数据//008//"
    pearson = readFileToArray(filepath + "outputMatrix3.txt")  # 皮尔逊矩阵， 第ij位置是第i个交易和第j个交易的相关系数
    txListAndOrigin = readTxAndFromFileToArray(filepath + "transaction_from.csv")  # 交易和来源的列表
    print("交易个数：" + str(len(txListAndOrigin)))

    # 应该对来源排序
    nodeSortList = []  # 节点顺序，用于标记
    txList = []  # 交易顺序的列表，用于标记
    for li in txListAndOrigin:
        txList.append(li[0])
    '''
    txDictClassifyByOrigin结构：{fromID:[tx1，tx2，]   ,  fromID:[tx3，tx4，tx5]   ,    fromID:[tx6，tx7]  }    
    记录每个节点产生的交易
    '''
    txDictClassifyByOrigin = dict()  # 字典  存放txListAndOrigin处理之后的结构，按fromID划分
    for index, tx in enumerate(txListAndOrigin):  # 不用判断交易index，完全一样的
        fromID = tx[1]
        if fromID not in txDictClassifyByOrigin:
            nodeSortList.append(fromID)
            txDictClassifyByOrigin[fromID] = []
            txDictClassifyByOrigin[fromID].append(index)
        else:
            txDictClassifyByOrigin[fromID].append(index)

    classifyNum = len(txDictClassifyByOrigin)
    print("实际发送源个数：" + str(classifyNum))

    print("具体情况:")
    for index, key in enumerate(txDictClassifyByOrigin.keys()):
        print("第 {} 个节点:{} 发出的交易数：{}".format(index + 1, key[0:8], len(txDictClassifyByOrigin[key])))

    result_true = []  # 真实分类情况
    for li in txListAndOrigin:
        num = nodeSortList.index(li[1])
        result_true.append(num)
    # 聚类
    clusterResultList = my_SpectralCoclustering(pearson, classifyNum*2)
    # clusterResultList=my_AffinityPropagation(pearson, classifyNum)

    purity = accuracy(result_true, clusterResultList)  # 计算聚类纯度 or 准确率
    ri, ari, f_beta = get_rand_index_and_f_measure(result_true, clusterResultList, beta=1.)
    print(f"purity:{purity}\nrand:{ri}\nA_rand:{ari}\nf1_score:{f_beta}")
